<template>
  <Card :title="'当前角色：' + roleName" size="small" class="share-card">
    <template #extra>
      <div class="btn-group">
        <Button type="primary" @click="addUsers()"><UserAddOutlined /> 添加用户</Button>
        <Button @click="$router.push({ path: '/rbac/roles' })"><LeftOutlined /> 返回</Button>
      </div>
    </template>
    <Table :rowKey="getRowKey" :columns="columns" :data-source="users" @resizeColumn="resizeColumn" :scroll="{ x: 500, y: tableHeight }" :pagination="pagerOption" @change="onPaged" size="small" bordered>
      <template #bodyCell="{ column, record }">
        <div v-if="column.key == 'op'">
          <Button type="primary" shape="round" danger @click="remove(record)"> <DeleteOutlined /> 删除 </Button>
        </div>
      </template>
    </Table>
  </Card>
  <userSelector ref="userEl" :roleId="roleId" @confirm="saveRoleUsers" />
</template>
<script setup>
  import { useStore } from 'vuex';
  import { useRoute, useRouter } from 'vue-router';
  import { ref, reactive, inject, computed, onMounted, defineAsyncComponent } from 'vue';
  import { Card, Table, Button } from 'ant-design-vue';
  import { UserAddOutlined, DeleteOutlined, LeftOutlined } from '@ant-design/icons-vue';

  const userSelector = defineAsyncComponent(() => import('./components/UserSelector.vue'));

  const $store = useStore();
  const $route = useRoute();
  const $router = useRouter();
  const $http = inject('$http');
  const $modal = inject('$modal');
  const $message = inject('$message');

  const userEl = ref();
  const roleId = ref(0);
  const roleName = ref('');
  const users = ref([]);

  const pagerOption = reactive({
    current: 1,
    pageSize: 20,
    defaultPageSize: 20,
    total: 0
  });
  const so = reactive({
    level: '',
    keywords: ''
  });
  const columns = reactive([
    {
      title: '序号',
      width: 30,
      resizable: false,
      align: 'center',
      customRender: ({ index }) => (pagerOption.current - 1) * pagerOption.pageSize + index + 1
    },
    { title: '账号', width: 80, resizable: true, dataIndex: 'Account' },
    { title: '用户名', width: 50, resizable: true, dataIndex: 'UserName' },
    { title: '邮箱', width: 150, resizable: true, dataIndex: 'EMail' },
    { title: '创建时间', width: 120, resizable: true, dataIndex: 'CreatedOn' },
    { title: '最后一次登录时间', width: 110, resizable: true, dataIndex: 'LastLogOn' },
    { key: 'op', align: 'center', fixed: 'right', width: 50 }
  ]);

  const tableHeight = computed(() => {
    return $store.state.area.content.height - 180;
  });

  function getRowKey(record) {
    return 'tr' + record.Id;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  function searchUsers(pg) {
    let index = 1;

    if (pg && pg.current) {
      index = pg.current;
      pagerOption.pageSize = pg.pageSize;
    }

    let searchObject = {
      pageIndex: index,
      pageSize: pagerOption.pageSize,
      account: so.account,
      userName: so.userName
    };

    $http.post(`/api/rbac/role/${roleId.value}/users`, searchObject).then(res => {
      users.value = res.datas;

      pagerOption.current = index || 1;
      pagerOption.total = res.total;
    });
  }

  function addUsers() {
    if (userEl.value) {
      userEl.value.show();
    }
  }

  function saveRoleUsers(userIds) {
    $http.post(`/api/rbac/role/${roleId.value}/addUsers`, userIds).then(res => {
      if (res.success) {
        $message.success('添加成功！');

        searchUsers();
      } else {
        $message.error({ key: 'save', content: res.message });
      }
    });
  }

  function remove(item) {
    $modal.confirm({
      title: '警告',
      content: '是否确定删除该用户？',
      onOk: () => {
        $http.delete(`/api/rbac/role/${roleId.value}/${item.Id}`).then(res => {
          if (res.success) {
            $message.success('删除成功！');

            searchUsers();
          } else {
            $message.error({ key: 'delete', content: res.message });
          }
        });
      }
    });
  }

  onMounted(() => {
    roleId.value = $route.query.id;
    roleName.value = $route.query.name;

    searchUsers();
  });
</script>
